package logger

import (
	"io"
	"os"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var Logger *zap.Logger

func InitLogger(logPath string, debug string) {
	fileWriter := &lumberjack.Logger{
		Filename:   logPath + "/server.log",
		MaxSize:    128,  // 单文件最大128MB
		MaxBackups: 60,   // 保留30天日志
		MaxAge:     30,   // 日志最长保留30天
		Compress:   true, // 压缩旧日志
		LocalTime:  true, // 使用本地时间
	}
	var syncers = []zapcore.WriteSyncer{zapcore.AddSync(fileWriter)}
	var level = zap.InfoLevel
	if debug == "debug" {
		syncers = append(syncers, zapcore.AddSync(os.Stdout))
		level = zap.DebugLevel
	}
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
	core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), zapcore.NewMultiWriteSyncer(syncers...), level)
	Logger = zap.New(core, zap.AddCaller())
	ginLogInit(logPath, debug)
}

func ginLogInit(logPath string, debug string) {
	gin.DisableConsoleColor()
	_ = os.Mkdir(logPath, os.ModePerm)
	f, err := os.Create(logPath + "/access.log")
	if err != nil {
		Logger.Error("log init error:", zap.Error(err))
	}
	if debug == "debug" {
		gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
	} else {
		gin.DefaultWriter = io.MultiWriter(f)
	}
}
